package avicit.bdp.dds.api.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.dto.BdpPrmEngineResourceDTO;
import avicit.bdp.common.service.service.BdpCommonService;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.common.utils.ConfigUtils;
import avicit.bdp.common.utils.DateUtils;
import avicit.bdp.common.utils.redis.RedisCacheHelper;
import avicit.bdp.dds.api.dto.NoteBookDTO;
import avicit.bdp.dds.api.dto.OrgDeptUser;
import avicit.bdp.dds.api.enums.ProjectTypeEnum;
import avicit.bdp.dds.api.enums.Status;
import avicit.bdp.dds.common.Constants;
import avicit.bdp.dds.dao.entity.Analysis;
import avicit.bdp.dds.dao.entity.DefaultProjectUser;
import avicit.bdp.dds.dao.entity.ProcessDefinition;
import avicit.bdp.dds.dao.entity.Project;
import avicit.bdp.dds.dao.entity.ProjectTable;
import avicit.bdp.dds.dao.entity.ProjectUser;
import avicit.bdp.dds.dao.entity.UdfFunc;
import avicit.bdp.dds.dao.mapper.ProjectMapper;
import avicit.bdp.dds.dao.mapper.ProjectUserMapper;
import avicit.bdp.dds.dao.mapper.UdfFuncMapper;
import avicit.bdp.dds.dispatch.enums.ExecutionStatus;
import avicit.bdp.dms.api.BdpPrmEngineResourceApi;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.SysDeptClient;
import avicit.platform6.api.system.SysRoleClient;
import avicit.platform6.api.system.SysUserClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.api.sysuser.dto.SysDept;
import avicit.platform6.api.sysuser.dto.SysRole;
import avicit.platform6.api.sysuser.dto.SysUser;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.properties.PlatformConstant;
import avicit.platform6.core.rest.msg.QueryRespBean;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * project service
 */
@Service
public class ProjectService extends BaseService<ProjectMapper, Project> {

    private final ProjectUserMapper projectUserMapper;
    private final ProjectUserService projectUserService;
    private final ProjectTableService projectTableService;
    private final AnalysisService analysisService;
    private final ProcessDefinitionService processDefinitionService;
    private final ProcessInstanceService processInstanceService;
    private final SysDeptClient sysDeptClient;
    private final SysUserClient sysUserClient;
    private final SysRoleClient sysRoleClient;
    private final DefaultProjectUserService defaultProjectUserService;
    private final BdpPrmEngineResourceApi bdpPrmEngineResourceApi;
    @Autowired
    private RedisCacheHelper redisCacheHelper;
    @Autowired
    private NoteBookService noteBookService;
    @Autowired
    private AlgoNodesService algoNodesService;
    @Autowired
    private UdfFuncMapper udfFuncMapper;
    @Autowired
    private ConvertColumnClient convertColumnClient;
    @Autowired
    private BdpCommonService bdpCommonService;

    @Autowired
    public ProjectService(
            AnalysisService analysisService,
            ProjectUserMapper projectUserMapper,
            ProjectUserService projectUserService,
            ProjectTableService projectTableService,
            ProcessDefinitionService processDefinitionService,
            ProcessInstanceService processInstanceService,
            DefaultProjectUserService defaultProjectUserService,
            SysRoleClient sysRoleClient,
            SysDeptClient sysDeptClient,
            SysUserClient sysUserClient,
            BdpPrmEngineResourceApi bdpPrmEngineResourceApi) {

        this.analysisService = analysisService;
        this.projectUserMapper = projectUserMapper;
        this.projectUserService = projectUserService;
        this.projectTableService = projectTableService;
        this.processDefinitionService = processDefinitionService;
        this.processInstanceService = processInstanceService;
        this.defaultProjectUserService = defaultProjectUserService;
        this.sysRoleClient = sysRoleClient;
        this.sysDeptClient = sysDeptClient;
        this.sysUserClient = sysUserClient;
        this.bdpPrmEngineResourceApi = bdpPrmEngineResourceApi;
    }

    public QueryRespBean<Project> getListForProjects(
            String keyWords, Integer pageNo, Integer pageSize) {

        QueryRespBean<Project> queryRespBean = new QueryRespBean<>();
        try {
            com.github.pagehelper.PageHelper.startPage(pageNo, pageSize);

            Page<Project> dataList = this.mapper.queryProjectListPaging("", keyWords);

            queryRespBean.setResult(dataList);
            BdpLogUtil.log4Query(queryRespBean);
            return queryRespBean;
        } catch (Exception e) {
            throw new BusinessException(e.getMessage(), e);
        }
    }

    public Map<String, Object> checkProjectAndAuth(
            String userId, Project project, String projectName) {
        Map<String, Object> result = new HashMap<>(8);
        if (project == null) {
            result.put(Constants.STATUS, Status.PROJECT_NOT_FOUNT);
        } else if (!checkReadPermission(userId, project)) {
            // check read permission
            result.put(Constants.STATUS, Status.USER_NO_OPERATION_PROJECT_PERM);
        } else {
            result.put(Constants.STATUS, Status.SUCCESS);
        }

        return result;
    }

    /**
     * check whether have read permission
     *
     * @param project project
     * @return true if the user have permission to see the project, otherwise return false
     */
    private boolean checkReadPermission(String userId, Project project) {
        int permissionId = queryPermission(userId, project);
        return (permissionId & Constants.READ_PERMISSION) != 0;
    }

    /**
     * query permission id
     */
    private int queryPermission(String userId, Project project) {

        if (StringUtils.isNotBlank(project.getCreatedBy()) && project.getCreatedBy().equals(userId)) {
            return Constants.ALL_PERMISSIONS;
        }
        // 项目成员权限
        ProjectUser projectUser = projectUserMapper.queryProjectRelation(project.getId(), userId);

        if (projectUser == null) {
            return 0;
        }

        return projectUser.getPerm();
    }

    /**
     * 查询数据空间列表
     */
    @Transactional(readOnly = true)
    public QueryRespBean<Project> getList(String keyWords, Integer pageNo, Integer pageSize) {
        QueryRespBean<Project> queryRespBean = new QueryRespBean<>();
        try {
            String userId = ThreadContextHelper.getUserId();
            if (StringUtils.isBlank(userId)) {
                userId = "1";
            }

            PageHelper.startPage(pageNo, pageSize);

            Page<Project> dataList = this.mapper.getList(userId, keyWords);
            List<Project> list = dataList.getResult();
            if (list != null && list.size() > 0) {
                for (Project project : list) {
                    // 组装userid返回前端
                    String userIds = "";
                    ProjectUser projectUser = new ProjectUser();
                    projectUser.setProjectId(project.getId());
                    List<ProjectUser> projectUsers = projectUserService.selectList(projectUser);
                    if (projectUsers != null && projectUsers.size() > 0) {
                        for (int i = 0; i < projectUsers.size(); i++) {
                            if (i == 0) {
                                userIds = projectUsers.get(i).getUserId();
                            } else {
                                userIds = userIds + "," + projectUsers.get(i).getUserId();
                            }
                        }
                        project.setUserIds(userIds);
                    }
                    if (userId.equals(project.getCreatedBy())) {
                        project.setCurrentUser(1);
                    } else {
                        project.setCurrentUser(0);
                    }
                }
            }
            queryRespBean.setResult(dataList);
            BdpLogUtil.log4Query(queryRespBean);
            return queryRespBean;
        } catch (Exception e) {
            throw new BusinessException(e.getMessage(), e);
        }
    }

    /**
     * 根据userId查询具有权限的项目空间
     */
    @Transactional(readOnly = true)
    public List<Project> getProjectByUserId(String userId) {
        try {
            return this.mapper.getProjectByUserId(userId);
        } catch (Exception e) {
            throw new BusinessException(e.getMessage(), e);
        }
    }

    /**
     * 新增数据空间列表
     */
    @Transactional(rollbackFor = Exception.class)
    public String insertProject(Project project) {
        try {
            project.setId(ComUtil.getId());
            project.setDefaulted(0);
            insertSelective(project);
            if (!StringUtils.isEmpty(project.getUserIds())) {
                bathInsertProjectUser(project.getUserIds(), project.getId());
            }
            // 存储引擎信息存放redis
            if (StringUtils.isNotBlank(project.getEngineResourceId())) {
                redisCacheHelper.set(
                        avicit.bdp.core.constant.Constants.PROJECT_RESOURCEID + project.getId(),
                        project.getEngineResourceId());
            }
            // 记录日志
            BdpLogUtil.log4Insert(project);
            return project.getId();
        } catch (Exception e) {
            throw new BusinessException(e.getMessage(), e);
        }
    }

    /**
     * 修改数据空间
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateProject(Project project) {
        try {
            updateByPrimaryKey(getProject(project));
            ProjectUser projectUser = new ProjectUser();
            projectUser.setProjectId(project.getId());
            projectUserService.delete(projectUser);
            if (!StringUtils.isEmpty(project.getUserIds())) {
                bathInsertProjectUser(project.getUserIds(), project.getId());
            }
        } catch (Exception e) {
            throw new BusinessException(e.getMessage(), e);
        }
    }

    /**
     * 删除数据空间
     *
     * @param id ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteProjectById(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new BusinessException("删除失败！传入的参数主键为null");
        }

        // 判断空间是否有任务，有无法删除
        ProcessDefinition processDefinitionQuery = new ProcessDefinition();
        processDefinitionQuery.setProjectId(id);
        List<ProcessDefinition> processDefinitionList =
                processDefinitionService.selectList(processDefinitionQuery);
        if (processDefinitionList != null && processDefinitionList.size() > 0) {
            throw new BusinessException("空间已创建任务，无法删除！");
        }

        // 判断空间是否有数据发布，有无法删除
        int dataResourceCount = this.mapper.selectCountDataResource(id);
        if (dataResourceCount > 0) {
            throw new BusinessException("空间有数据发布，无法删除！");
        }

        // 判断空间是否有notebook服务器，有无法删除
        NoteBookDTO noteBookDTO = new NoteBookDTO();
        noteBookDTO.setProjectId(id);
        Long notebookCount = noteBookService.selectCount(noteBookDTO);
        if (notebookCount > 0) {
            throw new BusinessException("空间存在Notebook服务，无法删除！");
        }

        try {
            // 记录日志
            Project project = selectByPrimaryKey(id);
            if (project == null) {
                throw new BusinessException("删除失败！对象不存在");
            }
            // 判断个人空间（如果没有其他空间则不允许删除）
            if (1 == project.getDefaulted()) {
                List<Project> list = this.mapper.getAllDevProjectList(project.getCreatedBy(), null, null);
                if (list.size() < 2) {
                    throw new BusinessException("删除失败！无其他数据空间，个人空间不能删除");
                }
            }

            BdpLogUtil.log4Delete(project);
            // 删除业务数据
            deleteByPrimaryKey(id);
            // 删除projectUser表中数据
            ProjectUser projectUser = new ProjectUser();
            projectUser.setProjectId(project.getId());
            projectUserService.delete(projectUser);
            // 删除关联数据源
            this.mapper.deleteDatasourceById(id);
            // 删除关联数据表
            // 只能删除非导入的模型
            this.mapper.deleteTableById(id, ProjectTable.IMPORTED_NEW);

            // 删除所有关系
            ProjectTable pTable = new ProjectTable();
            pTable.setProjectId(id);
            projectTableService.delete(pTable);
            // 删除analysis关联数据
            Analysis analysisQuery = new Analysis();
            analysisQuery.setProjectId(id);
            analysisService.delete(analysisQuery);
            // 删除notebook
            NoteBookDTO noteBookDel = new NoteBookDTO();
            noteBookDel.setProjectId(id);
            noteBookService.delete(noteBookDel);

            // 删除bdp_dds_nodes关联数据
            algoNodesService.deleteByProjectId(id);

            // 删除bdp_dds_udf
            UdfFunc udfQuery = new UdfFunc();
            udfQuery.setProjectId(id);
            udfFuncMapper.delete(udfQuery);

            // 删除redis的存储引擎信息
            redisCacheHelper.del(avicit.bdp.core.constant.Constants.PROJECT_RESOURCEID + project.getId());
        } catch (Exception e) {
            throw new BusinessException(e.getMessage(), e);
        }
    }

    /**
     * 私有方法 批量新增ProjectUser
     *
     * @param userIds   用户ID
     * @param projectId 项目空间ID
     */
    private void bathInsertProjectUser(String userIds, String projectId) {
        String[] userIdList = userIds.split(Constants.COMMA);
        for (String userId : userIdList) {
            ProjectUser insertQuery = new ProjectUser();
            insertQuery.setId(ComUtil.getId());
            insertQuery.setProjectId(projectId);
            insertQuery.setUserId(userId);
            insertQuery.setPerm(7);
            projectUserService.insertSelective(insertQuery);
        }
    }

    /**
     * 修改内部查询方法
     */
    private Project getProject(Project project) {
        Project oldDTO = selectByPrimaryKey(project.getId());
        if (oldDTO == null) {
            throw new BusinessException("数据不存在");
        }
        // 记录日志
        BdpLogUtil.log4Update(project, oldDTO);

        oldDTO.setName(project.getName());
        oldDTO.setRemark(project.getRemark());
        oldDTO.setProjectType(project.getProjectType());
        oldDTO.setEngineResourceId(project.getEngineResourceId());
        oldDTO.setSecretLevel(project.getSecretLevel());

        // 存储引擎信息存放redis
        if (StringUtils.isNotBlank(project.getEngineResourceId())) {
            redisCacheHelper.set(
                    avicit.bdp.core.constant.Constants.PROJECT_RESOURCEID + project.getId(),
                    project.getEngineResourceId());
        }
        return oldDTO;
    }

    /**
     * 概览数据空间列表——展示4条
     */
    public List<Project> getListFirstProject() {
        String userId = ThreadContextHelper.getUserId();
        if (StringUtils.isBlank(userId)) {
            userId = "1";
        }
        List<Project> list = this.mapper.getListFirstProject(userId);
        if (list != null && list.size() > 0) {
            for (Project project : list) {
                String userIds = "";
                ProjectUser projectUser = new ProjectUser();
                projectUser.setProjectId(project.getId());
                List<ProjectUser> projectUsers = projectUserService.selectList(projectUser);
                if (projectUsers != null && projectUsers.size() > 0) {
                    for (int i = 0; i < projectUsers.size(); i++) {
                        if (i == 0) {
                            userIds = projectUsers.get(i).getUserId();
                        } else {
                            userIds = userIds + "," + projectUsers.get(i).getUserId();
                        }
                    }
                    project.setUserIds(userIds);
                }
                if (userId.equals(project.getCreatedBy())) {
                    project.setCurrentUser(1);
                } else {
                    project.setCurrentUser(0);
                }
            }
        }
        return list;
    }

    /**
     * 判断数据空间名称是否重复
     */
    public boolean isSameName(String id, String name) {
        boolean flag = false;
        Project project = new Project();
        project.setName(name);
        project.setCreatedBy(ThreadContextHelper.getUserId());
        List<Project> list = selectList(project);
        if (list != null && list.size() > 0) {
            if (StringUtils.isBlank(id)) {
                flag = true;
            }
            for (Project dto : list) {
                if (!dto.getId().equals(id)) {
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }

    /**
     * 公共模型导入
     */
    @Transactional(rollbackFor = Exception.class)
    public void importCommonModel(String modelIds, String projectId, String typeId) {
        try {
            if (StringUtils.isBlank(modelIds) || StringUtils.isBlank(projectId)) {
                throw new BusinessException("参数为空");
            }
            String[] modelIdArr = modelIds.split(Constants.COMMA);
            for (String modelId : modelIdArr) {
                ProjectTable projectTable = new ProjectTable();
                projectTable.setId(ComUtil.getId());
                projectTable.setProjectId(projectId);
                projectTable.setTableId(modelId);
                projectTable.setTypeId(typeId);
                projectTable.setImported(ProjectTable.IMPORTED_COMMON);
                // 记录日志
                String logTitle = "从物理模型导入,modelId为：【" + modelIds + "】";
                BdpLogUtil.log("空间表管理模块", logTitle, PlatformConstant.OpType.insert);
                projectTableService.insertSelective(projectTable);
            }
        } catch (Exception e) {
            throw new BusinessException(e.getMessage(), e);
        }
    }

    /**
     * 获取人员信息
     */
    public List<OrgDeptUser> getUserList(String projectId) {

        // 项目空间id集合
        String userId = ThreadContextHelper.getUserId();
        if (StringUtils.isBlank(userId)) {
            userId = "1";
        }

        // 顶级节点
        List<OrgDeptUser> list = Lists.newArrayList();
        // List<OrgDeptUser> childList = Lists.newArrayList();
        Map<String, List<OrgDeptUser>> map = Maps.newHashMap();

        SysUser user = sysUserClient.getSysUserById(userId);
        SysDept dept = sysDeptClient.getSysDeptBySysDeptId(user.getDeptId());
        String orgId = dept.getOrgId();
        List<SysDept> sysDeptList = sysDeptClient.getSysDeptsByOrgId(orgId);
        if (sysDeptList != null && sysDeptList.size() > 0) {
            for (SysDept sysDept : sysDeptList) {
                OrgDeptUser orgDeptUser = new OrgDeptUser();
                orgDeptUser.setId(sysDept.getId());
                orgDeptUser.setName(sysDept.getDeptName());
                orgDeptUser.setType(1);
                if ("-1".equals(sysDept.getParentDeptId())) {
                    list.add(orgDeptUser);
                } else {
                    if (map.containsKey(sysDept.getParentDeptId())) {
                        List<OrgDeptUser> sysDepts = map.get(sysDept.getParentDeptId());
                        sysDepts.add(orgDeptUser);
                    } else {
                        List<OrgDeptUser> orgDeptUserList = Lists.newArrayList();
                        orgDeptUserList.add(orgDeptUser);
                        map.put(sysDept.getParentDeptId(), orgDeptUserList);
                    }
                }
            }
        }
        List<SysUser> sysUserList = sysUserClient.getAllSysUsers();

        // 查询projectId空间中的用户
        if (StringUtils.isNotEmpty(projectId)) {
            sysUserList = getProjectUserList(projectId, sysUserList);
        }

        if (sysUserList != null && sysUserList.size() > 0) {
            for (SysUser sysUser : sysUserList) {
                if ("0".equals(sysUser.getType())) { // 0 为实体用户
                    OrgDeptUser orgDeptUser = new OrgDeptUser();
                    orgDeptUser.setId(sysUser.getId());
                    orgDeptUser.setName(sysUser.getName());
                    orgDeptUser.setType(2);
                    orgDeptUser.setParentId(sysUser.getDeptId());
                    if (map.containsKey(sysUser.getDeptId())) {
                        List<OrgDeptUser> sysDepts = map.get(sysUser.getDeptId());
                        sysDepts.add(orgDeptUser);
                    } else {
                        List<OrgDeptUser> orgDeptUserList = Lists.newArrayList();
                        orgDeptUserList.add(orgDeptUser);
                        map.put(sysUser.getDeptId(), orgDeptUserList);
                    }
                }
            }
        }
        listConvert(list, map);

        return list;
    }

    private void listConvert(List<OrgDeptUser> list, Map<String, List<OrgDeptUser>> map) {
        for (OrgDeptUser orgDeptUser : list) {
            List<OrgDeptUser> orgDeptUserList = map.get(orgDeptUser.getId());
            if (orgDeptUserList != null && orgDeptUserList.size() > 0) {
                listConvert(orgDeptUserList, map);
                orgDeptUser.setChildren(orgDeptUserList);
            } else {
                orgDeptUser.setChildren(null);
            }
        }
    }

    /**
     * 查看空间中的人员
     *
     * @param projectId
     * @param allSysUserList
     * @return
     */
    public List<SysUser> getProjectUserList(String projectId, List<SysUser> allSysUserList) {
        List<SysUser> sysUserList = new ArrayList<>();

        ProjectUser projectUser = new ProjectUser();
        projectUser.setProjectId(projectId);
        List<ProjectUser> list = projectUserService.selectList(projectUser);

        if (CollectionUtils.isNotEmpty(list)) {
            List<String> userIdList =
                    list.stream().map(ProjectUser::getUserId).collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(allSysUserList)) {
                for (SysUser user : allSysUserList) {
                    if (userIdList.contains(user.getId())) {
                        sysUserList.add(user);
                    }
                }
            }
        }

        return sysUserList;
    }

    /**
     * 获取角色信息
     */
    public List<SysRole> getRoleList() {
        List<SysRole> roleList = new ArrayList<>();
        List<SysRole> list = sysRoleClient.getAllSysRoles();
        if (CollectionUtils.isNotEmpty(list)) {
            for (SysRole role : list) {
                if (!"0".equals(role.getRoleType())) {
                    roleList.add(role);
                }
            }
        }
        return roleList;
    }

    /**
     * 重点关注
     *
     * @param projectId 项目空间ID
     * @return 重点关注
     */
    public Map<String, Object> getFocus(String projectId) {
        Map<String, Object> map = Maps.newHashMap();
        String today = DateUtils.getSystemCurrentDate();
        Long fail = 0L;
        Long running = 0L;
        Long success = 0L;
        Long slow = 0L;
        Long definition = 0L;
        Long slowTime = ConfigUtils.getInstance().getLong("slowRunTime", 1800);

        if (StringUtils.isBlank(projectId)) {
            // 项目空间id集合
            List<String> projectIdList = Lists.newArrayList();
            String userId = ThreadContextHelper.getUserId();
            if (StringUtils.isBlank(userId)) {
                userId = "1";
            }
            List<Project> projectList = this.mapper.getProjectByUserId(userId);
            for (Project project : projectList) {
                projectIdList.add(project.getId());
            }
            if (CollectionUtils.isNotEmpty(projectIdList)) {
                fail =
                        processInstanceService.getDataCountByState(
                                today, projectIdList, ExecutionStatus.FAILURE.getCode());
                running =
                        processInstanceService.getDataCountByState(
                                today, projectIdList, ExecutionStatus.RUNNING_EXEUTION.getCode());
                success =
                        processInstanceService.getDataCountByState(
                                today, projectIdList, ExecutionStatus.SUCCESS.getCode());
                slow =
                        processInstanceService.getSlowCountByState(
                                today, projectIdList, ExecutionStatus.SUCCESS.getCode(), slowTime);
                definition = processDefinitionService.getDefinitionByProjectIds(projectIdList);
                map.put("projectCount", projectList.size());
            }
        } else {
            fail =
                    processInstanceService.getDataCountByProjectId(
                            today, projectId, ExecutionStatus.FAILURE.getCode());
            running =
                    processInstanceService.getDataCountByProjectId(
                            today, projectId, ExecutionStatus.RUNNING_EXEUTION.getCode());
            success =
                    processInstanceService.getDataCountByProjectId(
                            today, projectId, ExecutionStatus.SUCCESS.getCode());
            slow =
                    processInstanceService.getSlowCountByProjectId(
                            today, projectId, ExecutionStatus.SUCCESS.getCode(), slowTime);
            definition = processDefinitionService.getDefinitionByProjectId(projectId);
        }
        map.put("fail", fail);
        map.put("running", running);
        map.put("success", success);
        map.put("slow", slow);
        map.put("definition", definition);
        return map;
    }

    /**
     * 获取当前用户的所有项目
     *
     * @author xugb
     */
    public List<Project> getAllProjectList() {
        String userId = ThreadContextHelper.getUserId();
        if (StringUtils.isBlank(userId)) {
            userId = "1";
        }
        // 文档密级
        List<String> wordSecretList = ThreadContextHelper.getWordSecretList();
    /*if (StringUtils.isBlank(projectType)) {
        projectType = ProjectTypeEnum.DATA_DEV.getCode();
    }*/
        // 获取当前用户所有有数据开发任务的项目
        List<Project> dataList = this.mapper.getAllDevProjectList(userId, null, wordSecretList);
        if (dataList != null && dataList.size() > 0) {
            for (Project project : dataList) {
                String ids = project.getUserIds();
                if(StringUtils.isNotBlank(ids)) {
                    List<String> idList = Arrays.asList(ids.split(","));
                    String userNames = valueConvertUsernames(idList);
                    project.setUserNames(userNames);
                }
                if (userId.equals(project.getCreatedBy())) {
                    project.setCurrentUser(1);
                } else {
                    project.setCurrentUser(0);
                }
            }
        }

        String logTitle = "查看项目空间：【" + JSONObject.toJSONString(dataList) + "】";
        BdpLogUtil.log("项目空间管理模块", logTitle, PlatformConstant.OpType.select);
        return dataList;
    }

    private String valueConvertUsernames(List<String> idList) {
        List<String> userNameList = Lists.newArrayList();
        // 循环组装请求数据
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (String userId : idList) {
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, userId);
        }
        if (convertFormData.size() > 0) {
            // 获取请求结果
            Map<String, Map<String, String>> convertResultData =
                    convertColumnClient.replace(convertFormData);
            // 循环设置Alias或Name的值
            for (String userId : idList) {
                userNameList.add(BusinessUtil.convertFormat(
                        convertResultData, SystemConstant.USER, userId));
            }
        }
        String userNames = "";
        if (CollectionUtils.isNotEmpty(userNameList)) {
            for (int i = 0; i < userNameList.size(); i++) {
                userNames += userNameList.get(i);
                if (i < userNameList.size() - 1) {
                    userNames += ",";
                }
            }
        }
        return userNames;
    }

    public synchronized Project getDefaultProject() {
        String userId = ThreadContextHelper.getUserId();
        logger.info("userId: " + userId);
        if (StringUtils.isBlank(userId)) {
            userId = "1";
        }

        DefaultProjectUser query = new DefaultProjectUser();
        query.setUserId(userId);
        List<DefaultProjectUser> defaultProjectUserList = defaultProjectUserService.selectList(query);
        //
        if (!defaultProjectUserList.isEmpty()) {
            DefaultProjectUser defaultProjectUser = defaultProjectUserList.get(0);
            Project defaultProject = this.selectByPrimaryKey(defaultProjectUser.getDefaultProjectId());
            if (defaultProject != null) {
                return defaultProject;
            } else {
                return getUserProject(userId);
            }
        } else {
            return getUserProject(userId);
        }
    }

    private Project getUserProject(String userId) {
        List<Project> projects = this.mapper.getAllDevProjectList(userId, null, null);
        if (projects != null && projects.size() > 0) {
            Project project = projects.get(0);
            DefaultProjectUser insert = new DefaultProjectUser();
            insert.setId(ComUtil.getId());
            insert.setDefaultProjectId(project.getId());
            insert.setUserId(userId);
            defaultProjectUserService.insert(insert);
            return project;
        } else {
            Project project = new Project();
            String projectId = ComUtil.getId();
            project.setId(projectId);
            project.setName("个人空间");
            project.setDefaulted(1);
            // 默认是公开密级
            project.setSecretLevel(bdpCommonService.getMinSecretLevel());
            // 查询默认存储引擎
            BdpPrmEngineResourceDTO defaultEngineResource =
                    bdpPrmEngineResourceApi.findDefaultEngineResource(BdpPrmEngineResourceDTO.TYPE_STORAGE);
            if (defaultEngineResource != null) {
                project.setEngineResourceId(defaultEngineResource.getId());
            } else {
                return null;
            }
            DefaultProjectUser insertQuery = new DefaultProjectUser();
            insertQuery.setId(ComUtil.getId());
            insertQuery.setDefaultProjectId(projectId);
            insertQuery.setUserId(userId);
            this.insert(project);
            defaultProjectUserService.insert(insertQuery);
            return this.selectByPrimaryKey(projectId);
        }
    }

    public synchronized Project getPhmDefaultProject(String projectType, String phmProjectId, String phmProjectName) {
        String userId = ThreadContextHelper.getUserId();
        logger.info("userId: " + userId);
        if (StringUtils.isBlank(userId)) {
            userId = "1";
        }
        if (StringUtils.isBlank(projectType)) {
            projectType = ProjectTypeEnum.PHM_FLOW.getCode();
        }

        DefaultProjectUser query = new DefaultProjectUser();
        query.setUserId(userId);
        query.setProjectType(projectType);
        if (StringUtils.isNotBlank(phmProjectId)) {
            query.setDefaultProjectId(phmProjectId);
        }
        List<DefaultProjectUser> defaultProjectUserList = defaultProjectUserService.selectList(query);

        if (!defaultProjectUserList.isEmpty()) {
            DefaultProjectUser defaultProjectUser = defaultProjectUserList.get(0);
            Project defaultProject = this.selectByPrimaryKey(defaultProjectUser.getDefaultProjectId());
            if (defaultProject != null) {
                return defaultProject;
            } else {
                return getUserProject(userId, projectType, phmProjectId, phmProjectName);
            }
        } else {
            return getUserProject(userId, projectType, phmProjectId, phmProjectName);
        }
    }

    private Project getUserProject(String userId, String projectType, String phmProjectId, String phmProjectName) {
        //phm工程，先查询是否已经创建该工程id的项目
        if (projectType.equals(ProjectTypeEnum.PHM_FLOW.getCode()) && StringUtils.isNotBlank(phmProjectId)) {
            Project project = this.selectByPrimaryKey(phmProjectId);
            if (project != null) {
                DefaultProjectUser insert = new DefaultProjectUser();
                insert.setId(ComUtil.getId());
                insert.setDefaultProjectId(project.getId());
                insert.setUserId(userId);
                insert.setProjectType(projectType);
                defaultProjectUserService.insert(insert);
                return project;
            }

        } else if (!projectType.equals(ProjectTypeEnum.PHM_FLOW.getCode())) {
            List<Project> projects = this.mapper.getAllDevProjectList(userId, projectType, null);
            if (projects != null && projects.size() > 0) {
                Project project = projects.get(0);
                DefaultProjectUser insert = new DefaultProjectUser();
                insert.setId(ComUtil.getId());
                insert.setDefaultProjectId(project.getId());
                insert.setUserId(userId);
                insert.setProjectType(projectType);
                defaultProjectUserService.insert(insert);
                return project;
            }
        }
        //如果没有，则自动创建
        Project project = new Project();
        String projectId = ComUtil.getId();
        String name = "个人空间";
        if (projectType.equals(ProjectTypeEnum.PHM_FLOW.getCode()) && StringUtils.isNotBlank(phmProjectId)) {
            projectId = phmProjectId;
            name = phmProjectName;
        }
        project.setId(projectId);
        project.setName(name);
        project.setDefaulted(1);
        project.setProjectType(projectType);
        DefaultProjectUser insertQuery = new DefaultProjectUser();
        insertQuery.setId(ComUtil.getId());
        insertQuery.setDefaultProjectId(projectId);
        insertQuery.setUserId(userId);
        insertQuery.setProjectType(projectType);
        this.insert(project);
        defaultProjectUserService.insert(insertQuery);
        return this.selectByPrimaryKey(projectId);
    }


    public synchronized void setDefaultProject(String projectId) {
        if (StringUtils.isBlank(projectId)) {
            throw new BusinessException("请检查参数");
        }
        Project project = this.selectByPrimaryKey(projectId);
        if (project == null) {
            throw new BusinessException("对象不存在");
        }
        String userId = ThreadContextHelper.getUserId();
        if (StringUtils.isBlank(userId)) {
            userId = "1";
        }
        DefaultProjectUser query = new DefaultProjectUser();
        query.setUserId(userId);
        List<DefaultProjectUser> defaultProjectUserList = defaultProjectUserService.selectList(query);
        if (defaultProjectUserList != null && !defaultProjectUserList.isEmpty()) {
            DefaultProjectUser defaultProjectUser = defaultProjectUserList.get(0);
            defaultProjectUser.setDefaultProjectId(projectId);
            defaultProjectUserService.updateByPrimaryKeySelective(defaultProjectUser);
        } else {
            DefaultProjectUser insert = new DefaultProjectUser();
            insert.setId(ComUtil.getId());
            insert.setDefaultProjectId(projectId);
            insert.setUserId(userId);
            defaultProjectUserService.insert(insert);
        }
    }

    public String getResourceEngineIdByTaskId(String taskId) {
        return this.mapper.getResourceEngineIdByTaskId(taskId);
    }

    /**
     * 根据ID查询Project
     *
     * @param id 工程ID
     * @return 工程对象
     */
    public Project getProjectById(String id) {
        return this.selectByPrimaryKey(id);
    }

    public Integer selectResourceType(String projectId) {
        return this.mapper.selectResourceType(projectId);
    }

    /**
     * 判断当前用户是否为空间创建人
     *
     * @param projectId
     * @return
     */
    public Boolean projectCreateAble(String projectId) {
        if (StringUtils.isBlank(projectId)) {
            throw new BusinessException("请检查参数");
        }
        Project project = this.selectByPrimaryKey(projectId);
        if (project == null) {
            throw new BusinessException("对象不存在");
        }
        String userId = ThreadContextHelper.getUserId();
        if (StringUtils.isBlank(userId)) {
            userId = "1";
        }
        if (userId.equals(project.getCreatedBy())) {
            return true;
        }
        return false;
    }
}
